package config

import (
	"biz_alert/pkg/db"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/BurntSushi/toml"
	"go.uber.org/zap"
)

var C = &Config{}

type Config struct {
	Database     db.DatabaseConf `json:"database" toml:"database"`
	AlertChannel AlertChannel    `json:"alert_channel" toml:"alert_channel"`
	Cron         string          `json:"cron" toml:"cron"`
	Logger       LoggerConf      `json:"logger" toml:"logger"`
}

type AlertChannel struct {
	Wechat struct {
		Webhook string `json:"webhook" toml:"webhook"`
	} `json:"wechat" toml:"wechat"`
}

type LoggerConf struct {
	Env    string `json:"env" toml:"env"`
	Level  string `json:"level" toml:"level"`
	Output string `json:"output" toml:"output"`
}

func (c *Config) String() string {
	dj, err := json.Marshal(c)
	if err != nil {
		return ""
	}
	return string(dj)
}

func LoadCongFromToml(cfgFile string) error {
	if cfgFile == "" {
		return errors.New("the config cannot be empty")
	} else {
		if _, err := toml.DecodeFile(cfgFile, C); err != nil {
			return err
		}
	}
	zapLevel := zap.NewAtomicLevel()
	if err := zapLevel.UnmarshalText([]byte(C.Logger.Level)); err != nil {
		panic(err.Error())
	}
	var zapConf zap.Config

	if env := C.Logger.Env; env == "dev" {
		zapConf = zap.NewDevelopmentConfig()
	} else {
		zapConf = zap.NewProductionConfig()
	}
	zapConf.Level = zapLevel

	if C.Logger.Output != "" {
		zapConf.OutputPaths = []string{C.Logger.Output}
		zapConf.ErrorOutputPaths = []string{C.Logger.Output}
	}
	if logger, err := zapConf.Build(); err != nil {
		panic(err.Error())
	} else {
		zap.RedirectStdLog(logger)
		zap.ReplaceGlobals(logger)
	}
	zap.L().Info(fmt.Sprintf("loaded config: %s", cfgFile))
	return nil
}
